package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import jdk.nashorn.internal.codegen.DumpBytecode;
import lombok.SneakyThrows;
import model.Article;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: 首页
 * @author: chengbaiyi
 * @create: 2022-05-24 18:53
 */
@WebServlet("/artlist")
public class ArticleListServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Article> data = new ArrayList<>();
        // 得到前端参数
        String currPage = req.getParameter("cp");
        String pageSize = req.getParameter("ps");
        int cp = 1;     // 当前页码
        int ps = 4;     // 每页最多显示文章数
        if (!StrUtil.isBlank(currPage)) {
            cp = Integer.parseInt(currPage);
        }
        if (!StrUtil.isBlank(pageSize)) {
            ps = Integer.parseInt(pageSize);
        }
        // 使用分页查询查询数据库内容
        Connection connection = DBUtils.getConnection();
        String sql = "select * from article order by aid desc limit ? offset ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, ps);
        statement.setInt(2, (cp - 1) * ps);
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
            Article article = new Article();
            article.setAid(resultSet.getInt("aid"));
            article.setUid(resultSet.getInt("uid"));
            article.setTitle(resultSet.getString("title"));
            String create_time = resultSet.getString("create_time");
            article.setCreate_time(create_time.substring(0, create_time.lastIndexOf(".")));
            String context = resultSet.getString("context");
            context = context.replace("#", "");
            int maxLen = Math.min(50, context.length());
            article.setDesc(context.substring(0, maxLen));
            data.add(article);
        }
        DBUtils.close(resultSet, statement, connection);
        // 将数据返回给前端
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200, data, "")));
    }
}
